<template>
    <div style=" height: inherit;">
        <el-row style=" border-radius: 5px; padding:5px; height:100%">
            <el-col :span="18">
                <a-flex justify="space-between" align="center" style="width: 100%; padding: 10px;">
                    <div>
                        <el-checkbox v-model='ctx.用血记录' label='用血记录' @change="newChat" />
                        <el-checkbox v-model='ctx.血液库存' label='血液库存' @change="newChat" :disabled="true" />
                    </div>
                    <div>
                        <el-button type="primary" @click="export2excel">
                            导出
                        </el-button>
                        <el-button type="success" @click="saveSql">
                            保存为智能表格
                        </el-button>
                    </div>
                </a-flex>
                <el-auto-resizer style="border:1px solid #ebeef5; border-radius: 5px; padding:5px; height:90%">
                    <template #default="{ height, width }">
                        <el-table-v2 :columns="ctx.tableData.columns" :data="ctx.tableData.data" :sort-by="sortState"
                            @column-sort="onSort" v-loading="loading" fixed :width="width" :height="height" />
                    </template>
                </el-auto-resizer>
            </el-col>
            <el-col :span="6" style="margin:0px 0px;  padding: 10px; height:100%">
                <div style="margin:0px 0px; padding: 10px; height:80%; border:1px solid #ebeef5; border-radius: 5px;">
                    <!-- 用户输入的问题 -->
                    <a-flex v-for="item in userQuestionList" style="margin-bottom: 10px; width:100%" justify="flex-end"
                        align="center">
                        <div style="background-color: #EFF6FF; padding:8px; border-radius: 10px; margin-left: 50px">
                            {{ item.content }}
                        </div>
                    </a-flex>
                    <!-- TODO 系统提示 -->
                    <a-flex style="border-radius: 6px; width:100%" justify="flex-start" align="center">
                        <el-progress :text-inside="true" :stroke-width="26" :percentage="percentage2"
                            :format="thinkFormat" style=" padding:8px; width: 300px;" v-show="loading" />
                    </a-flex>
                </div>
                <div style="margin:10px 0px;  padding: 0px 0px; background-color:#FFFFFF00;">
                    <el-input v-model="userQuestion" @keyup.enter.native='search' :autosize="{ minRows: 3 }"
                        type="textarea" placeholder="请输入查询统计需求" />
                    <p style="margin: 5px;" />
                    <a-flex style="width: 100%; padding:5px" justify="space-between" align="center">
                        <MkButtonAdd @click="newChat"> 新的对话 </MkButtonAdd>
                        <MkButtonQuery @click="search" :loading="loading"> </MkButtonQuery>
                    </a-flex>
                </div>
            </el-col>
        </el-row>
    </div>
</template>
<script lang="ts" setup>
import { SqlQueryApi, SqlQueryPrompt, SqlQueryOutput, ElTableV2Column } from '/@/api/bas/SqlQuery';
import { BasPrintDraftApi } from '/@/api/bas/BasPrintDraft';
import { TableV2SortOrder } from 'element-plus'
import type { SortBy } from 'element-plus'
import { clog, isNull, showSuccess } from '/@/utils';
import { usePageQuery, useLoadingFetch } from '/@/hooks'
import { useI18n } from 'vue-i18n'
import table2excel from 'js-table2excel'
import { enumCode } from '/@/const'

const { t, locale } = useI18n()

const ctx = reactive({
    tableData: { sql: '', columns: [], data: [] } as SqlQueryOutput,
    用血记录: true,
    血液库存: true,
    检验样品: false,
    采血记录: false,
});

const systemPrompt = ref({ role: 'system', content: '' })
const userQuestion = ref('')
const userQuestionList = ref<SqlQueryPrompt[]>([]) // 多轮会话

const { fetch, loading } = useLoadingFetch(SqlQueryApi.queryData);

onMounted(async () => {
    ctx.tableData = { sql: '', columns: [], data: [] }
    newChat();
})


//// TODO 点击不同的标签, 先查询数据库显示前100条, 同步更新systemPrompt
const newChat = () => {
    if (ctx.采血记录) {
        // 血站
        systemPrompt.value.content = window.__env__.systemPrompt.prefix + window.__env__.systemPrompt.caiXueXinXi;
    } else if (ctx.检验样品) {
        // 疾控
        systemPrompt.value.content = window.__env__.systemPrompt.prefix + window.__env__.systemPrompt.jianYanYangPinXinXi;
    } else {
        // 血库
        systemPrompt.value.content = window.__env__.systemPrompt.prefix + window.__env__.systemPrompt.xueYeKuCun;
        if (ctx.用血记录) {
            systemPrompt.value.content += window.__env__.systemPrompt.yongXueJiLu;
        }
    }
    userQuestionList.value = []
}
const search = async () => {
    if (isNull(userQuestion.value)) {
        return;
    }
    userQuestionList.value.push({ role: 'user', content: userQuestion.value.trim() }) // 多轮会话
    // ctx.tableData = { columns: [], data: [] }
    userQuestion.value = ""
    let messages = [systemPrompt.value, ...userQuestionList.value];
    clog("messages", messages)
    showThink();
    ctx.tableData = await fetch(messages)

    // 列名转中文
    ctx.tableData.columns = ctx.tableData.columns.map((item: ElTableV2Column) => {
        const translated = t(`aiQuery.${item.title.trim()}`);
        item.title = translated !== `aiQuery.${item.title.trim()}` ? translated : item.title;
        return item;
    })
    // ctx.tableData = await SqlQueryApi.queryData()
}

// 排序
const sortState = ref<SortBy>({
    key: 'column-0',
    order: TableV2SortOrder.ASC,
})

const onSort = (sortBy: SortBy) => {
    ctx.tableData.data = ctx.tableData.data.reverse()
    sortState.value = sortBy;
}

// 导出
const export2excel = () => {
    table2excel(ctx.tableData.columns, ctx.tableData.data, 'table.xlsx')
}

// 保存sql
const saveSql = async () => {
    await BasPrintDraftApi.add({ category: enumCode.PrintCategory.AI, title: "Ai查询", sql1: ctx.tableData.sql, template: '<table border="1px">  <thead>    <tr>      <th v-for="(value, key) in t1[0]" :key="key">{{ key }}</th>    </tr>  </thead>  <tbody>    <tr v-for="(user, index) in t1" :key="index">      <td v-for="(value, key) in user" :key="key">{{ value }}</td>    </tr>  </tbody></table>' })
    showSuccess()
}

// 系统提示
const percentage2 = ref(0)
const showThink = () => {
    percentage2.value = 5
    setInterval(() => {
        if (percentage2.value < 95) {
            percentage2.value = (percentage2.value % 100) + 2
        }
    }, 500)
}

const thinkFormat = (percentage: number) => {
    let thinkMgs = "...";
    if (percentage > 5) {
        thinkMgs = "请求大模型...";
    }
    if (percentage > 20) {
        thinkMgs = "正在思考...";
    }
    if (percentage > 50) {
        thinkMgs = "生成查询...";
    }
    if (percentage > 70) {
        thinkMgs = "执行查询...";
    }
    return thinkMgs;
}

// TODO 侧边栏收缩
const collapsed = ref<boolean>(false);

</script>
<style scoped></style>